﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.OrderModules
{
    public class OrderUpdaterRegister
    {
        int rows;
        public NormalDataUpdater<OrderModel> GetOrderUpdater()
        {
            NormalDataUpdater<OrderModel> systemDataUpdater = new NormalDataUpdater<OrderModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataUpdating += CustomerExist;
            systemDataUpdater.DataUpdating += StateValid;
            systemDataUpdater.DataUpdating += SalesPointExist;
            systemDataUpdater.DataUpdating += TypeExist;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void StateValid(object sender,DataValidationEventArgs<OrderModel> e)
        {
            string message;
            if (e.Insert.State != Definition.STATE_NORMAL)
            {
                OrderDetailFetcher orderDetailFetcher = new OrderDetailFetcher();
                IList<OrderDetailModel> details = orderDetailFetcher.ListByMainId(e.Insert.Site, e.Insert.AutoId, out message, out rows);
                int detailCounter = details.Count;
                if (detailCounter == 0)
                {
                    e.Message = String.Format("提审状态下必须具备明细信息[{0}]", e.Insert.OrderCode);
                    e.Cancle = true;
                    return;
                }
                var total = from detail in details select detail.Amount;
                if(Math.Abs(total.Sum()-e.Insert.Total)>(decimal)0.01)
                {
                    e.Message = "单头金额与单身金额之和不相等";
                    e.Cancle = true;
                    return;
                }
                if (e.Insert.PropertyUpdated.Contains("OrderType") ||
                     e.Insert.PropertyUpdated.Contains("OrderCode") ||
                     e.Insert.PropertyUpdated.Contains("SalesDate") ||
                     e.Insert.PropertyUpdated.Contains("SalesId") ||
                     e.Insert.PropertyUpdated.Contains("CustomerId") ||
                     e.Insert.PropertyUpdated.Contains("SalesPointId")
                    )
                {
                    e.Message = String.Format("单据内容不允许修改{0}", e.Insert.OrderCode);
                    e.Cancle = true;
                    return;
                }
            }
            if (e.Insert.State == Definition.STATE_NORMAL||e.Insert.State==Definition.STATE_READY)
            {
                if (e.Insert.AutoId > 0)
                {
                    ServiceBonusFetcher serviceBonusFetcher = new ServiceBonusFetcher();
                    int bonusCounter = serviceBonusFetcher.ListByOrder(e.Insert.Site, e.Insert.AutoId, out message, out rows).Count;
                    if (bonusCounter > 0)
                    {
                        e.Message = String.Format("下游存在服务奖金单据，不允许反审核");
                        e.Cancle = true;
                        return;
                    }
                    PayFetcher payFetcher = new PayFetcher();
                    int payCounter = payFetcher.ListByOrder(e.Insert.Site, e.Insert.AutoId, out message, out rows).Count;
                    if (payCounter > 0)
                    {
                        e.Message = String.Format("下游存在付款单据，不允许反审核");
                        e.Cancle = true;
                        return;
                    }
                    DesignerBonusFetcher designerBonusFetcher = new DesignerBonusFetcher();
                    int dBonusCounter = designerBonusFetcher.ListByOrder(e.Insert.Site, e.Insert.AutoId, out message, out rows).Count;
                    if (dBonusCounter > 0)
                    {
                        e.Message = String.Format("下游存在设计奖金单据，不允许反审核");
                        e.Cancle = true;
                        return;
                    }
                    SalesBonusFetcher salesBonusFetcher = new SalesBonusFetcher();
                    int sBonusCounter = salesBonusFetcher.ListByOrder(e.Insert.Site, e.Insert.AutoId, out message, out rows).Count;
                    if (sBonusCounter > 0)
                    {
                        e.Message = String.Format("下游存在销售奖金单据，不允许反审核");
                        e.Cancle = true;
                        return;
                    }
                    DeliveryDetailFetcher dFetcher = new DeliveryDetailFetcher();
                    int dCounter = dFetcher.ListByOrder(e.Insert.Site, e.Insert.AutoId, out message, out rows).Count;
                    if (dCounter > 0)
                    {
                        e.Message = String.Format("下游存在销售物流单据，不允许反审核");
                        e.Cancle = true;
                        return;
                    }
                }
            }
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<OrderModel> e)
        {
            if (e.Delete.State != Definition.STATE_NORMAL)
            {
                e.Cancle = true;
                e.Message = String.Format("[{0}]正在生效，不能删除", e.Delete.AutoId);
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<OrderModel> e)
        {
            OrderFetcher OrderFetcher = new OrderFetcher();
            string message = "";
            OrderModel Order = OrderFetcher.GetByCode(e.Insert.Site, e.Insert.OrderCode, out message);
            if (Order != null && Order.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被占用", Order.OrderCode);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<OrderModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.OrderCode))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if(String.IsNullOrWhiteSpace(e.Insert.CustomerName))
            {
                e.Message = "客户名不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.DeliveryAddress))
            {
                e.Message = "交货地址不能为空";
                e.Cancle = true;
                return;
            }
            DateTime dt = DateTime.Now;
            if(!DateTime.TryParse(e.Insert.SalesDate, out dt))
            {
                e.Message = String.Format("订单日期{0}有误",dt);
                e.Cancle = true;
                return;
            }
            if (!DateTime.TryParse(e.Insert.DeliveryDate, out dt))
            {
                e.Cancle = true;
                e.Message = String.Format("交货日期{0}不正确", e.Insert.DeliveryDate);
                return;
            }
        }
        private void TypeExist(object sender,DataValidationEventArgs<OrderModel> e)
        {
            string message;
            OrderTypeFetcher orderTypeFetcher = new OrderTypeFetcher();
            if(orderTypeFetcher.Get(e.Insert.Site,e.Insert.OrderType,out message)==null)
            {
                e.Message = "单别不存在";
                e.Cancle = true;
                return;
            }
        }
        private void CustomerExist(object sender, DataValidationEventArgs<OrderModel> e)
        {
            string message;
            CustomerFetcher cFetcher = new CustomerFetcher();
            if (cFetcher.Get(e.Insert.Site, e.Insert.CustomerId, out message) == null)
            {
                e.Message = "客户不存在";
                e.Cancle = true;
                return;
            }
        }
        private void SalesPointExist(object sender, DataValidationEventArgs<OrderModel> e)
        {
            string message;
            SalesPointFetcher spFetcher = new SalesPointFetcher();
            if (spFetcher.Get(e.Insert.Site, e.Insert.SalesPointId, out message) == null)
            {
                e.Message = "门店不存在";
                e.Cancle = true;
                return;
            }
        }
    }
}
